//
//  ChangeEnvironmentManager.m
//  MobileCaiLocal
//
//  Created by simon on 2021/3/30.
//  Copyright © 2021 com.Chs. All rights reserved.
//  注意：Preprocessor Macros项预编译宏只支持项目中，SDK只支持DEBUG/Release二种宏；

#import "ChangeEnvironmentManager.h"
#import "ChangeEnvDefine.h"

NSNotificationName const kEnvironmentChangeNotification = @"kEnvironmentChangeNotification";
///切换什么环境的key
static NSString *const ud_ChangeEnvironmentApiEnv = @"changeApiEnvKey";

@interface ChangeEnvironmentManager ()

@property (nonatomic, strong) NSMutableArray *hostMArray;

@property (nonatomic, copy) NSString *x_prodHost;
@property (nonatomic, copy) NSString *x_preHost;
@property (nonatomic, copy) NSString *x_testHost;
@property (nonatomic, copy) NSString *x_dailyHost;
@property (nonatomic, copy) NSString *x_devHost;
@property (nonatomic, copy) NSString *x_localHost;
@property (nonatomic, assign) ApiEnv debugDefaultApiEnv;
@property (nonatomic, assign) ApiEnv profileDefaultApiEnv;
@property (nonatomic, assign) ApiEnv releaseDefaultApiEnv;

//生产配置是否只用生产环境;如果也用切换环境，则false，记录之前的环境选择。如果不用切换环境，则true。
@property (nonatomic, assign) BOOL prodIsOnlyUseOnLineHost;

@end


@implementation ChangeEnvironmentManager


+ (instancetype)sharedInstance
{
    static ChangeEnvironmentManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
        instance.debugDefaultApiEnv = ApiEnvDev;
        instance.profileDefaultApiEnv = ApiEnvDev;
        instance.releaseDefaultApiEnv = ApiEnvProd;
        instance.prodIsOnlyUseOnLineHost = YES;
    });
    return instance;
}


- (NSMutableArray *)hostMArray{
    
    if (!_hostMArray) {
        _hostMArray = [NSMutableArray array];
    }
    return _hostMArray;
}

+ (ChangeEnvironmentManager *)startWithDebugDefaultApiEnv:(ApiEnv)debugDefaultApiEnv
                                     profileDefaultApiEnv:(ApiEnv)profileDefaultApiEnv
{
    
    return [self startWithProdHost:Api_DomainName_Release
                             preHost:Api_DomainName_Pre
                          testHost:nil
                           dailyHost:Api_DomainName_Daily
                             devHost:Api_DomainName_Dev
                         localHost:nil
                  debugDefaultApiEnv:debugDefaultApiEnv
                profileDefaultApiEnv:profileDefaultApiEnv];
}

+ (ChangeEnvironmentManager *)startWithProdHost:(nullable NSString *)prod
                                        preHost:(nullable NSString *)pre
                                       testHost:(nullable NSString *)test
                                      dailyHost:(nullable NSString *)daily
                                        devHost:(nullable NSString *)dev
                                      localHost:(nullable NSString *)local
                             debugDefaultApiEnv:(ApiEnv)debugDefaultApiEnv
                           profileDefaultApiEnv:(ApiEnv)profileDefaultApiEnv
{
    ChangeEnvironmentManager *manager =  [ChangeEnvironmentManager sharedInstance];
    [manager.hostMArray removeAllObjects];
    manager.x_prodHost = prod;
    manager.x_preHost = pre;
    manager.x_testHost = test;
    manager.x_dailyHost = daily;
    manager.x_devHost = dev;
    if (prod) {
        ZXChangeEnvironmentModel *model = [[ZXChangeEnvironmentModel alloc] init];
        model.envType = @"online";
        model.title =@"生产环境";
        model.hostUrl = prod;
        [manager.hostMArray addObject:model];
    }
    else if (pre) {
        ZXChangeEnvironmentModel *model = [[ZXChangeEnvironmentModel alloc] init];
        model.envType = @"pre";
        model.title =@"预发环境";
        model.hostUrl = pre;
        [manager.hostMArray addObject:model];
    }
    else if (test) {
        ZXChangeEnvironmentModel *model = [[ZXChangeEnvironmentModel alloc] init];
        model.envType = @"test";
        model.title =@"测试环境";
        model.hostUrl = test;
        [manager.hostMArray addObject:model];
    }
    else if (daily) {
        ZXChangeEnvironmentModel *model = [[ZXChangeEnvironmentModel alloc] init];
        model.envType = @"daily";
        model.title =@"日常环境";
        model.hostUrl = daily;
        [manager.hostMArray addObject:model];
    }
    else if (dev) {
        ZXChangeEnvironmentModel *model = [[ZXChangeEnvironmentModel alloc] init];
        model.envType = @"dev";
        model.title =@"开发环境";
        model.hostUrl = dev;
        [manager.hostMArray addObject:model];
    }
    else if (dev) {
        ZXChangeEnvironmentModel *model = [[ZXChangeEnvironmentModel alloc] init];
        model.envType = @"local";
        model.title =@"本地环境";
        model.hostUrl = local;
        [manager.hostMArray addObject:model];
    }
    manager.debugDefaultApiEnv = debugDefaultApiEnv;
    manager.profileDefaultApiEnv = profileDefaultApiEnv;
    return manager;
}

///设置默认构建配置环境为debug:ApiEnv.apiEnvDev;
///SDK不支持这DEBUG宏，无法做判断
- (void)setDefaultBuildConfiguration{
    //#ifdef DEBUG
    //    [self setBuildConfiguration:BuildConfigurationDebug];
    //#elif PROFILE
    //    //SDK不支持其它配置参数,不会进来，所以即使是profile也是走release配置；
    //    //一旦设置后，也会导致后续setBuildConfiguration设置profile格式不起作用；
    //    [self setBuildConfiguration:BuildConfigurationProfile];
    //#else
    //    [self setBuildConfiguration:BuildConfigurationRelease];
    //#endif
    self.buildConfiguration =BuildConfigurationDebug;
}


/// 设置初始化构建配置环境。1）当是buildConfigurationDebug、buildConfigurationProfile时，
/// 获取apiEnv环境值，如果本地有值，则不设置；
/// 如果是apiEnvUnknown没值，则使用BuildConfiguration配置的环境值。
/// 2）当是buildConfigurationRelease时，如果apiEnv不是生产环境，则始终设置为生产环境。
- (void)setBuildConfiguration:(BuildConfiguration)buildConfiguration{
    _buildConfiguration = buildConfiguration;
    ApiEnv apiEnv = [ChangeEnvironmentManager apiEnv];
    ChangeEnvironmentManager *manager =  [ChangeEnvironmentManager sharedInstance];
    switch (buildConfiguration) {
            //Debug构建配置下，如果没有值，则设置默认值
        case BuildConfigurationDebug:
            if (apiEnv == ApiEnvUnknown) {
                [ChangeEnvironmentManager storeWithApiEnv:manager.debugDefaultApiEnv];
            }
            NSLog(@"BuildConfigurationDebug");
            break;
            //Profile构建配置下，如果没有值，则设置默认值
        case BuildConfigurationProfile:
            NSLog(@"BuildConfigurationProfile");
            if (apiEnv == ApiEnvUnknown) {
                [ChangeEnvironmentManager storeWithApiEnv:manager.profileDefaultApiEnv];
            }
            break;
            // buildConfigurationRelease
            // manager.prodIsOnlyUseOnLineHost == true:如果apiEnv不是生产环境，则始终设置为生产环境。
            // 否则，也使用切换环境功能，和其它配置一样的逻辑。
        default:
            NSLog(@"BuildConfigurationRelease");
            if (manager.prodIsOnlyUseOnLineHost == true) {
                    if (apiEnv != ApiEnvProd) {
                        [ChangeEnvironmentManager storeWithApiEnv:ApiEnvProd];
                    }
                  }
            else {
                if (apiEnv == ApiEnvUnknown) {
                    [ChangeEnvironmentManager storeWithApiEnv:manager.releaseDefaultApiEnv];
                }
            }
            break;
    }
}


//需要一定时间，如果马上杀死进场，则无法存储。
+ (void)storeWithApiEnv:(ApiEnv)apiEnv
{
    [[NSUserDefaults standardUserDefaults]setInteger:apiEnv forKey:ud_ChangeEnvironmentApiEnv];
}


//如果该值不存在或不能转换为整数，则返回0。
+ (ApiEnv)apiEnv{
    ApiEnv apiEnv = [[NSUserDefaults standardUserDefaults]integerForKey:ud_ChangeEnvironmentApiEnv];
    return apiEnv;
}



+ (void)changeEnvironmentActionWithApiEnv:(ApiEnv)apiEnv
{
    [self storeWithApiEnv:apiEnv];
    [[NSNotificationCenter defaultCenter]postNotificationName:kEnvironmentChangeNotification object:nil];
}


+ (ApiEnv)switchEnvStringToApiEnv:(NSString *)envType{
    ApiEnv apiEnv = ApiEnvUnknown;
    if([envType isEqualToString:@"online"])
    {
        apiEnv = ApiEnvProd;
    }
    else if([envType isEqualToString:@"pre"])
    {
        apiEnv = ApiEnvPre;
    }else if([envType isEqualToString:@"test"])
    {
        apiEnv = ApiEnvTest;
    }else if([envType isEqualToString:@"daily"])
    {
        apiEnv = ApiEnvDaily;
    }else if([envType isEqualToString:@"dev"])
    {
        apiEnv = ApiEnvDev;
    }else if([envType isEqualToString:@"local"])
    {
        apiEnv = ApiEnvLocal;
    }
    return apiEnv;
}



- (NSString *)prodHost{
    return self.x_prodHost;
}

- (NSString *)preHost{
    return self.x_preHost;
}

- (NSString *)testHost{
    return self.x_testHost;
}

- (NSString *)dailyHost{
    return self.x_dailyHost;
}

- (NSString *)devHost{
    return self.x_devHost;
}

- (NSString *)localHost{
    return self.x_localHost;
}

+ (NSString *)apiEnvHTTPBaseURL{
    
    ApiEnv apiEnv = [self apiEnv];
    NSString *host = nil;
    switch (apiEnv) {
        case ApiEnvProd:
            host = [ChangeEnvironmentManager sharedInstance].prodHost;
            break;
        case ApiEnvPre:
            host = [ChangeEnvironmentManager sharedInstance].preHost;
            break;
        case ApiEnvTest:
            host = [ChangeEnvironmentManager sharedInstance].testHost;
            break;
        case ApiEnvDaily:
            host = [ChangeEnvironmentManager sharedInstance].dailyHost;
            break;
        case ApiEnvDev:
            host = [ChangeEnvironmentManager sharedInstance].devHost;
            break;
        case ApiEnvLocal:
            host = [ChangeEnvironmentManager sharedInstance].localHost;
            break;
        default:
            break;
    }
    return host;
}


+ (NSArray<ZXChangeEnvironmentModel *> *)allApiEnvConfigu{
    ChangeEnvironmentManager *manager =  [ChangeEnvironmentManager sharedInstance];
    return manager.hostMArray;
}



@end
